package com.dky.satell.rocketmq.consumer.service;

import cn.hutool.core.util.StrUtil;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.dky.satell.entity.MessageConfig;
import com.dky.satell.kafka.model.MessageWrapper;
import com.dky.satell.kafka.producer.KafkaProducer;
import com.dky.satell.rocketmq.consumer.RocketMQConsumerInit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 监听
 *
 * @author lihaobin
 * @version 1.0
 * @date 2021/4/19 21:22
 */
@Slf4j
@Component
public class RocketMQListener implements MessageListener {

    @Autowired
    private KafkaProducer kafkaProducer;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        try {
            log.info("RocketMQ 采集, topic:[{}], message:[{}]", message.getTopic(), StrUtil.str(message.getBody(), "utf-8"));
            String body = StrUtil.str(message.getBody(), "utf-8");
            ConcurrentHashMap<String, MessageConfig> topicMessageConfigMap = RocketMQConsumerInit.getTopicMessageConfigMap();
            MessageConfig messageConfig = topicMessageConfigMap.get(message.getTopic());
            MessageWrapper wrapper = new MessageWrapper();
            wrapper.setMessageConfig(messageConfig);
            wrapper.setPayload(body);
            kafkaProducer.sendMessage(wrapper);
        } catch (Exception e) {
            log.error("RocketMQListener.consume error", e);
        }
        //如果想测试消息重投的功能,可以将Action.CommitMessage 替换成Action.ReconsumeLater
        return Action.CommitMessage;
    }

}
